# -*- coding: utf-8 -*-
# @File     : get_project_report_data.py
# @Author   : bingjia
# @Time     : 2020/9/24 13:14
# @Desc     : 获取生成报告的项目数据

import os
import datetime
from django.apps import apps
from pyecharts import Bar, Pie, Line, Style, Overlap, Radar


# os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'operation_back.settings.settings')
# from django.core.wsgi import get_wsgi_application
#
# application = get_wsgi_application()

current_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))


def get_project_report_data(project_ref):
    """
    获取项目报告数据
    :param: project_ref
    :return:
    """

    data = {}

    defectModel = apps.get_model("checks", "Defect")
    defectTypeModel = apps.get_model("checks", "DefectType")
    project = apps.get_model("projects", "Project").objects.get(slug=project_ref)
    src_data = apps.get_model("datas", "SrcData").objects.get(project=project)

    "缺陷数量"
    defect_number = defectModel.objects.filter(project=project, defect__type="0").count()
    "缺陷图片数量"
    defect_image_number = defectModel.objects.filter(project=project, defect__type="0").distinct("location").count()
    "缺陷占比"
    defect_prop = float('%.4f' % (defect_image_number / src_data.data_size)) * 100
    "缺陷类型"
    defect_type_list = list(
        set([x.name for x in defectTypeModel.objects.filter(defect_type__project=project, type="0")]))

    max_count = 0
    max_defect_type = None
    defect_type_number = []
    defect_table = [["类型", "数量", "占比"]]

    for defect_type in defect_type_list:
        count = defectModel.objects.filter(project=project, defect__name=defect_type, defect__type="0").count()

        if count > max_count:
            max_count = count
            max_defect_type = defect_type

        prop = round(float('%.3f' % (count / src_data.data_size)) * 100, 2)

        defect_table.append(
            [defect_type, str(count), str(prop) + "%"])

        defect_type_number.append(count)

    "分析建议"
    impact = {"环境影响": ['dust', 'flora'], "鸟类影响": ['shit'], "硬件影响": ['break', 'strip']}
    max_defect_type_impact = [x for x in list(impact.keys()) if max_defect_type in impact[x]][0]

    defect_table.append(['正常', str(src_data.data_size - defect_image_number),
                         round(float('%.4f' % ((src_data.data_size - defect_image_number) / src_data.data_size)) * 100,
                               2)])

    advice_table = [["缺陷类型", "修复建议"]]
    for defect_type in defect_type_list:
        advice_table.append(
            [defect_type, defectTypeModel.objects.get(name=defect_type, type='0').advice])

    "分布柱状图"
    defect_type_number.append(src_data.data_size - defect_image_number)
    defect_type_list_temp = defect_type_list[:]
    defect_type_list_temp.append("normal")

    style = Style(height=300, width=500)

    bar = Bar('', **style.init_style)
    bar.add('缺陷条形', defect_type_list_temp, defect_type_number, mark_line=["average"], mark_point=['min', 'max'])

    line = Line()
    line.add('缺陷折线', defect_type_list_temp, defect_type_number, effect_scale=8)

    overlap = Overlap(height=280, width=450)
    overlap.add(bar)
    overlap.add(line)
    overlap.render(path=os.path.join(current_path, 'images', 'bar_image.png'))

    "占比饼状图"
    pie = Pie('', title_pos='center', width=500)
    kwargs = dict(
        name="",
        attr=defect_type_list_temp,
        value=defect_type_number,
        radius=[0, 75],
        label_text_color=None,
        is_label_show=True,
        is_more_utils=True,
        legend_orient="vertical",
        legend_pos="left"
    )
    pie.add(**kwargs)
    pie.render(path=os.path.join(current_path, 'images', 'pie_image.png'))
    "历时运维图"

    "得分雷达图"
    c_schema = [
        {"name": "环境影响", "max": 100, "min": 0},
        {"name": "鸟类影响", "max": 100, "min": 0},
        {"name": "人为影响", "max": 100, "min": 0},
        {"name": "硬件影响", "max": 100, "min": 0},
        {"name": "时长影响", "max": 100, "min": 0},
        {"name": "雷雨影响", "max": 100, "min": 0},
    ]
    value = [[50, 70, 95, 80, 95, 95]]
    radar = Radar('', width=500)
    radar.config(c_schema=c_schema, radar_text_size=15, yaxis_line_width=1)
    radar.add("", value, item_color='#EE4000', symbol_size=10,
              symbol='roundRect', area_color='#EE4000', area_opacity=0.4,
              legend_top='left', legend_text_size=15, line_width=3)
    radar.render(os.path.join(current_path, 'images', 'radar_image.png'))

    "主页数据"
    data["home"] = {
        "name": "无人机智能光伏运维报告",
        "serial": "GF-" + str(
            datetime.datetime.now().year) + "-" + str(
            apps.get_model("projects", "Project").objects.filter(start_date__year='2021').count()).zfill(4),
        "reportName": project.name + "运维报告",
        "dataFrom": "无人机智能光伏运维平台"
    }

    "项目简介"
    data["title"] = {
        "title": "一、项目简介",
        "content": project.description
    }

    "项目信息"
    data["title2"] = {
        "title": "二、项目信息",
        "content": {
            "sub_title_1": {
                "title": "1、项目信息",
                "content": [
                    ["项目名称", project.name, "", ""],
                    ["项目负责人", project.owner.full_name, "运营时间", str(project.start_date).split(" ")[0]],
                    ["所属公司", project.company, "", ""],
                    ["公司地址", project.location, "", ""]]
            },
            "sub_title_2": {
                "title": "2、设备信息",
                "content": [
                    ["设备", "型号"],
                    ["无人机型号", project.uav.name],
                    ["镜头型号", project.camera.name]
                ]
            },
            "sub_title_3": {
                "title": "3、运维团队",
                "content": [
                    ["角色", "姓名"],
                    ["运维负责人", "薛晓冰"],
                    ["飞手", "蔡毓剑"]
                ]
            },
            "sub_title_4": {
                "title": "4、数据信息",
                "content": [
                    ["项目名称", project.name, "", ""],
                    ["拍摄时间", str(project.start_date).split(" ")[0], "结束时间",
                     str(project.end_date).split(" ")[0]],
                    ["飞行架次", str(project.sorties) + "次", "飞行时间", str(project.fly_time) + "小时"],
                    ["可见光图片数", str(src_data.data_size) + "张", "热成像图片数", str(src_data.data_size) + "张"],
                    ["天气情况", project.weather, "", ""],
                ]
            }
        }
    }

    "项目诊断"
    data["title3"] = {
        "title": "三、项目诊断",
        "content": {
            "content": "该项目检测光伏数据量【" + str(
                src_data.data_size) + "】张，检测到的缺陷类型总计" + str(len(defect_type_list)) + "个类别，缺陷数量" + str(
                defect_image_number) + "张，缺陷占比达到" + str(defect_prop) + "%。",
            "table": defect_table,

            "sub_title_1": {
                "title": "1、柱状图",
                "content": "bar_image.png"
            },
            "sub_title_2": {
                "title": "2、饼状图",
                "content": "pie_image.png"
            },
            "sub_title_3": {
                "title": "3、历史运维",
                "content": "pie_image.png"
            },
        }
    }

    "分析建议"
    data["title4"] = {
        "title": "四、分析建议",
        "content": {
            "sub_title_1": {
                "title": "1、缺陷分析",
                "content": "该项目缺陷类别中，【" + max_defect_type + "】占比最大，属于可修复性缺陷，该类缺陷形成原因主要是【" + max_defect_type_impact + "】。",
                "image": "radar_image.png"
            },
            "sub_title_2": {
                "title": "2、修复建议",
                "content": advice_table,
                "attention": "注意：相应修复建议以及修复视频可在光伏运维平台光伏主页查看。"
            }
        }
    }

    "样例图片"
    data["title5"] = {
        "title": "五、样例图片",
        "content": {
            "flora": {
                "title": "1、草木遮挡",
                "image": "flora.jpg"
            },
            "dust": {
                "title": "2、灰尘积累",
                "image": "dust.jpg"
            },
            "shit": {
                "title": "3、鸟类粪便",
                "image": "shit.jpg"
            },
            "strip": {
                "title": "4、条状缺陷",
                "image": "strip.jpg"
            },
            "break": {
                "title": "5、板面损坏",
                "image": [
                    {"image": "break.jpg"},
                    {"image": "break1.jpg"}
                ]
            },
        }
    }

    return data

# print(get_project_report_data("ce_shi_xiang_mu"))
